import { Card, Breadcrumb, Radio, DatePicker, Select, Form, Button, Table, Tag, Space, Pagination, Popconfirm } from "antd"
import { EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { Link, useNavigate } from "react-router-dom"
import locale from 'antd/es/date-picker/locale/zh_CN'
import useChannel from "@/hooks/useChannel"
import { useEffect, useState } from "react"
import { delArticleListApi, getArticleListApi } from "@/apis/article"

const Article = () => {
  const navigate = useNavigate()
  // 获取频道列表
  const {channelsList} = useChannel() 
  // 日期范围
  const { RangePicker } = DatePicker
  // 枚举实现审核判断
  const status = {
    1:<Tag color="warning">审核中</Tag>,
    2:<Tag color="success">审核通过</Tag>
  }
  // 确认删除函数
  const onConfirm = (data) => {
    delArticleListApi(data.id)
    setReqData({
      ...reqData
    })
  }
  // 准备列数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width:120,
      render:cover => {
        const imageUrl = '@/assets/atu.png'
        return <img src={imageUrl || img404} width={80} height={60} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      width:220
    },
    {
      title: '状态',
      dataIndex: 'status',
      // 也可用三元运算符
      render: data => status[data]
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            {/* shape 设置按钮形状 */}
            <Button 
              type="primary" 
              shape="circle" 
              icon={<EditOutlined />}
              onClick={() => navigate(`/publish?id=${data.id}`)}
            />
            <Popconfirm 
              title = '是否确认删除' 
              okText = '确认'
              cancelText = '取消' 
              onConfirm={() => onConfirm(data)}
            >
              <Button type="primary" danger shape="circle" icon={<DeleteOutlined />}/>
            </Popconfirm>
            
          </Space>
        )
      }
    },
  ]
  // 准备表格数据
  const data = [
    {
      id: '8218',
      comment_count: 0,
      cover: {
        images: [],
      },
      like_count: 0,
      pubdate: '2019-03-11 09:00:00',
      read_count: 2,
      status: 2,
      title: 'wkwebview离线化加载h5资源解决方案'
    }
  ]
  // 筛选功能
  // 筛选本质：给请求列表接口传递不同的参数
  const [reqData, setReqData] = useState({
    status:'',
    channel_id:'',
    begin_pubdate:'',
    end_pubdate:'',
    page:1,
    per_page:4
  })
  // 获取文章列表
  const [articleList, setArticleList] = useState([])
  // 筛选到的条数
  const [count, setCount] = useState(0)
  useEffect(() => {
    const getarticleList = async () => {
      const res = await getArticleListApi(reqData)
      setArticleList(res.data.results)
      setCount(res.data.total_count)
    }
    getarticleList()
  },[reqData])

  const onFinish = (formValue) => {
    setReqData({
      // 保留reqData 中已有的数据，仅更新需要修改的字段
      ...reqData,
      status,
      channel_id,
      begin_pubdate:formValue.date[0].format('YYYY-MM-DD'),
      end_pubdate:formValue.date[1].format('YYYY-MM-DD')
    })
  }
  // 分页跳转
  const pageChange = (page) => {
    setReqData({
      ...reqData,
      // 修改传参依赖项，引发数据重新获取列表渲染
      page
    })
  }

  return (
    <div className="article">
      <Card title={
        <Breadcrumb items={[
          { title:<Link to='/'>首页</Link> },
          { title:'文章列表' }
        ]}/>
      }
        style={{marginBottom:20}}
      >
        <Form validateTrigger='onBlur' initialValues={{status:''}} onFinish={onFinish}> 
          <Form.Item label="状态" name='status'>
            <Radio.Group
              
              options={[
                { value: '', label: '全部' },
                { value: 0, label: '草稿' },
                { value: 2, label: '审核通过' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              { required: true, message: '请选择频道' },
            ]}
          >
            {/* 下拉菜单选择频道 */}
            <Select size="middle" placeholder="请选择文章频道" style={{ width: 120 }} 
              options={ channelsList.map(item => ({
                value:item.id, label:item.name
              }))}
            />
          </Form.Item>
              
          <Form.Item label="日期" name="date">
            {/* 传入locale属性控制中文显示 */}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item label={null} style={{marginLeft:40}}>
            {/* block 让按钮占据父容器的整个宽度 */}
            <Button type="primary" htmlType="submit" size="middle">
            筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`根据筛选条件共查询到 ${count || 1} 条结果`}>
        <Table rowKey="id" columns={columns} dataSource={articleList || data} 
          pagination={{
            align:"center", 
            defaultCurrent:1, 
            total:count, 
            // 每页条数
            pageSize: reqData.per_page,
            onChange:pageChange
          }}
        />
      </Card>
    </div>
  )
}

export default Article